안녕하세요 해당 제품 관련해서 유튜브 영상 보고 코드를 작성했는데요
초음파 배선에 문제인지 코드의 문제인지 제품동작이 유튜브 영상과 맞지 않습니다.
(유튜브 영상 내 경기장에서 장애물 인지시 약간의 후진을 하고 방향을 틀고 전진하는 영상)
확인 부탁드립니다. 영상의 코드도 메일로 보내주시면 감사하겠습니다.
작성코드
#include <SoftwareSerial.h>
#include <AFMotor.h>
AF_DCMotor motor_L(1);
AF_DCMotor motor_R(4);
int i;
//초음파센서 출력핀(trig)과 입력핀(echo), 변수, 함수 선언 //
int TrigPin = A0;
int EchoPin = A1;
long duration, distance;
void Obstacle_Check();
void Distance();
void Forward();
void Backward();
void Right();
void Left();
void Stop();
void setup() {
Serial.begin(9600); // PC와의 시리얼 통신속도
Serial.println("Eduino Smart Car Start!");
pinMode(EchoPin, INPUT); // EchoPin 입력
pinMode(TrigPin, OUTPUT); // TrigPin 출력
motor_L.setSpeed(160);
motor_L.run(RELEASE);
motor_R.setSpeed(180);
motor_R.run(RELEASE);
}
void loop() {
Forward();
delay(100);
Obstacle_Check();
}
//장애물 확인 및 회피 방향 결정//
void Obstacle_Check() {
int val = random(2);
Distance();
Serial.println(distance);
while (distance < 200) {
if (distance < 180) {
Backward();
delay(250);
Stop();
delay(50);
Distance();
}
else{
if (val ==0) {
Right();
delay(400);
}
else if (val ==1) {
Left();
delay(400);
}
Distance();
}
}
}
//거리 감지//
void Distance() {
digitalWrite(TrigPin, LOW);
delay(2);
digitalWrite(TrigPin, HIGH); // trigPin에서 초음파 발생(echoPin도 HIGH)
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
duration = pulseIn(EchoPin, HIGH); // echoPin이 HIGH를 유지한 시간을 저장 한다.
distance = ((float)(340 * duration)/1000) /2;
delay(5);
}
//방향 제어 함수//
void Forward() {
motor_L.run(FORWARD); motor_R.run(FORWARD);
for (i=0; i<200; i=i+20) {
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
for (i=0;i<200;i=i-20){
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
void Backward() {
motor_L.run(BACKWARD); motor_R.run(BACKWARD);
for (i=0; i<200; i=i+20) {
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
for (i=0;i<200;i=i-20){
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
void Right() {
motor_L.run(FORWARD); motor_R.run(BACKWARD);
for (i=0;i<180;i=i+20){
//j = i*1.3; if(j>=200) j = 200;
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
for (i=180; i<0; i=i-20){
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
void Left() {
motor_L.run(BACKWARD); motor_R.run(FORWARD);
for (i=0;i<180;i=i+20){
//j = i*1.3; if(j>=200) j = 200;
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
for (i=180; i<0; i=i-20){
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
void Stop() {
motor_L.run(RELEASE); motor_R.run(RELEASE);
for (i=200; i>=0; i=i-20) {
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
강의자료 96P의 결선회로도 참조하여 조립해주세요